package com.movecar.ui;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import BLLocationCallbacker.DialogItemSelectCallbacker;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.movecar.R;
import com.movecar.dialog.CustomDialog;
import com.movecar.dialog.MoveCarDialogBuilder;
import com.movecar.listview.MyListView;
import com.movecar.model.CloudCoinsBean;
import com.movecar.utils.Alert;
import com.movecar.utils.AppConfig;
import com.movecar.utils.DataStore;
import com.movecar.utils.HttpPostRequestAsyncTask;
import com.movecar.utils.RequestResultCallback;
import com.movecar.utils.imageloader.Constants;
import com.movecar.widget.CustomProgressDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 云豆
 * 
 * @author Zhao.JQ
 * 
 */
@SuppressLint("NewApi")
public class CloudCoinsActivity extends Activity implements OnClickListener, OnItemClickListener,
		DialogItemSelectCallbacker {

	private CustomProgressDialog progressDialog = null;

	private TextView coins_count, cash_count;
	private ImageLoader imageLoader = null;

	private CloudCoinsBean mCloudCoinsBean;
	private MyListView mListView;
	private List<CloudCoinsBean> mCloudCoinsBeanList;
	private DataAdapter adapter;
	private RelativeLayout main_relative, deal_navi_new_tip, reward_navi_new_tip;
	private String strFlag = "1";
	private Button reward, deal;
	private String coin_reward_share, coin_reward_praise, coin_reward_comment, coin_reward_hotShare,
			coin_exchange_recharge, coin_exchange_getCash, coin_exchange_join, coin_reward_redbag;
	private List<String> positionList = null;
	private List<String> rewardPositionList = null;
	private ImageView btn_to_cash;
	private AlertDialog mDialogChoosePicture;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cloud_coins);
		imageLoader = ImageLoader.getInstance();

		coin_reward_share = getIntent().getStringExtra("coin_reward_share");
		coin_reward_praise = getIntent().getStringExtra("coin_reward_praise");
		coin_reward_comment = getIntent().getStringExtra("coin_reward_comment");
		coin_reward_hotShare = getIntent().getStringExtra("coin_reward_hotShare");
		coin_exchange_recharge = getIntent().getStringExtra("coin_exchange_recharge");
		coin_exchange_getCash = getIntent().getStringExtra("coin_exchange_getCash");
		coin_exchange_join = getIntent().getStringExtra("coin_exchange_join");
		coin_reward_redbag = getIntent().getStringExtra("coin_reward_redbag");
		positionList = new ArrayList<String>();
		rewardPositionList = new ArrayList<String>();
		if (!"".equals(coin_reward_share)) {
			rewardPositionList.add("coin_reward_share");
		}
		if (!"".equals(coin_reward_praise)) {
			rewardPositionList.add("coin_reward_praise");
		}
		if (!"".equals(coin_reward_comment)) {
			rewardPositionList.add("coin_reward_comment");
		}
		if (!"".equals(coin_reward_hotShare)) {
			rewardPositionList.add("coin_reward_hotShare");
		}

		if (!"".equals(coin_reward_redbag)) {
			rewardPositionList.add("coin_reward_redbag");
		}
		if (!"".equals(coin_exchange_recharge)) {
			positionList.add("coin_exchange_recharge");
		}
		if (!"".equals(coin_exchange_getCash)) {
			positionList.add("coin_exchange_getCash");

		}
		if (!"".equals(coin_exchange_join)) {
			positionList.add("coin_exchange_join");
		}

		initView();
	}

	@SuppressLint("SetJavaScriptEnabled")
	private void initView() {
		TextView title = (TextView) findViewById(R.id.title);
		title.setText("云豆");
		Button btn_left = (Button) findViewById(R.id.btn_left);
		btn_left.setVisibility(View.VISIBLE);
		btn_left.setOnClickListener(this);
		coins_count = (TextView) findViewById(R.id.coins_count);
		cash_count = (TextView) findViewById(R.id.cash_count);
		mListView = (MyListView) findViewById(R.id.mListView);
		main_relative = (RelativeLayout) findViewById(R.id.main_relative);
		deal_navi_new_tip = (RelativeLayout) findViewById(R.id.deal_navi_new_tip);
		reward_navi_new_tip = (RelativeLayout) findViewById(R.id.reward_navi_new_tip);
		reward = (Button) findViewById(R.id.reward);
		deal = (Button) findViewById(R.id.deal);
		btn_to_cash = (ImageView) findViewById(R.id.btn_to_cash);
		reward.setOnClickListener(this);
		deal.setOnClickListener(this);
		btn_to_cash.setOnClickListener(this);
		startProgressDialog();
		getSelfCoinDetail();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// 账号管理
		case R.id.btn_left:
			finish();
			break;
		case R.id.reward:
			reward.setBackgroundResource(R.drawable.reward);
			deal.setBackgroundResource(R.drawable.deal_click);
			strFlag = "1";
			positionList.clear();
			reward_navi_new_tip.setVisibility(View.GONE);
			mListView.setVisibility(View.GONE);

			getSelfCoinDetail();
			break;
		case R.id.deal:
			reward.setBackgroundResource(R.drawable.reward_click);
			deal.setBackgroundResource(R.drawable.deal);
			strFlag = "2";
			deal_navi_new_tip.setVisibility(View.GONE);
			rewardPositionList.clear();
			mListView.setVisibility(View.GONE);
			getSelfCoinDetail();
			break;
		case R.id.btn_to_cash:
			startProgressDialog();
			checkPassword();

			break;
		default:
			break;
		}

	}

	@SuppressWarnings("unchecked")
	private void getSelfCoinDetail() {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); //
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "selfCoinDetailNew1")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("strFlag", strFlag));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				String result = (String) object;

				Gson gson = new Gson();
				try {
					mCloudCoinsBean = gson.fromJson(result, CloudCoinsBean.class);
				} catch (Exception e) {
					return;
				}
				if (null != mCloudCoinsBean) {
					mListView.setVisibility(View.VISIBLE);
					coins_count.setText("共有云豆" + mCloudCoinsBean.getCoinCount());
					cash_count.setText("￥" + mCloudCoinsBean.getRMB());
					if (null != mCloudCoinsBean.getDetailArr()) {
						Type type = new TypeToken<List<CloudCoinsBean>>() {
						}.getType();
						Gson gson1 = new Gson();
						Object fromJson1 = gson1.fromJson(mCloudCoinsBean.getDetailArr(), type);
						try {
							mCloudCoinsBeanList = (List<CloudCoinsBean>) fromJson1;
						} catch (Exception e) {

						}
						main_relative.setVisibility(View.VISIBLE);
						adapter = new DataAdapter(CloudCoinsActivity.this, mCloudCoinsBeanList);
						mListView.setAdapter(adapter);
						mListView.setOnItemClickListener(CloudCoinsActivity.this);
						if ((positionList.contains("coin_exchange_recharge")
								|| positionList.contains("coin_exchange_getCash") || positionList.contains("coin_exchange_join"))
								&& deal_navi_new_tip.getVisibility() != View.GONE) {
							deal_navi_new_tip.setVisibility(View.VISIBLE);
						} else {
							deal_navi_new_tip.setVisibility(View.GONE);

						}
						if ((rewardPositionList.contains("coin_reward_redbag")
								|| rewardPositionList.contains("coin_reward_share")
								|| rewardPositionList.contains("coin_reward_praise")
								|| rewardPositionList.contains("coin_reward_comment") || rewardPositionList.contains("coin_reward_hotShare"))
								&& reward_navi_new_tip.getVisibility() != View.GONE) {
							reward_navi_new_tip.setVisibility(View.VISIBLE);
						} else {
							reward_navi_new_tip.setVisibility(View.GONE);
						}

					}
				} else {
					Alert.error(CloudCoinsActivity.this, "系统异常");
				}

			}

			@Override
			public void onFail(String exception) {

				stopProgressDialog();
				Alert.error(CloudCoinsActivity.this, "与服务器连接失败，请检查网络");

			}
		}, CloudCoinsBean.class, AppConfig.USER).execute(params);
	}

	// 检查是否设置密码
	@SuppressWarnings("unchecked")
	private void checkPassword() {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); //
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "queryCashCodeNew1")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				String result = (String) object;

				Gson gson = new Gson();
				try {
					mCloudCoinsBean = gson.fromJson(result, CloudCoinsBean.class);
				} catch (Exception e) {
					return;
				}
				if (null != mCloudCoinsBean) {

					if ("".equals(mCloudCoinsBean.getCashCode())) {
						CustomDialog.Builder customBuilder = new CustomDialog.Builder(CloudCoinsActivity.this);
						ImageView img = new ImageView(CloudCoinsActivity.this);
						img.setImageResource(R.drawable.ic_launcher);
						customBuilder.setImgIcon(img).setMessage("您尚未设置交易密码！")

						.setPositiveButton("现在设置", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								Intent intent = new Intent(CloudCoinsActivity.this,
										CloudCoinsRechargePasswordActivity.class); // 创建一个意图
								startActivityForResult(intent, 0);
								dialog.dismiss();

							}
						}).setNegativeButton("以后再说", new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {

								dialog.dismiss();

							}
						});
						customBuilder.create().show();

					} else {
						Intent intent = new Intent(CloudCoinsActivity.this,
								CloudCoinsRechargeEditPasswordActivity.class); // 创建一个意图
						intent.putExtra("cashCode", mCloudCoinsBean.getCashCode());
						startActivityForResult(intent, 0);// 开始意图

					}
				} else {
					Alert.error(CloudCoinsActivity.this, "系统异常");
				}

			}

			@Override
			public void onFail(String exception) {

				stopProgressDialog();
				Alert.error(CloudCoinsActivity.this, "与服务器连接失败，请检查网络");

			}
		}, CloudCoinsBean.class, AppConfig.USER).execute(params);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onActivityResult(int, int,
	 * android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 0) {
			if (resultCode == RESULT_OK) {

				(mDialogChoosePicture = MoveCarDialogBuilder.buidlListDialog(CloudCoinsActivity.this, "", new String[] {
						"话费充值", "提现到银行卡" }, CloudCoinsActivity.this)).show();

			}
		}
	}

	class DataAdapter extends BaseAdapter {

		private LayoutInflater inflater;
		private ViewHolder viewHolder = null;
		private List<CloudCoinsBean> dataList;

		DataAdapter(Activity activity, List<CloudCoinsBean> dataList) {

			this.dataList = dataList;
			inflater = LayoutInflater.from(activity);
		}

		@Override
		public int getCount() {

			return dataList.size();
		}

		@Override
		public Object getItem(int arg0) {

			return dataList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {

			return arg0;
		}

		@Override
		public View getView(final int position, View view, ViewGroup arg2) {

			if (view == null) {
				viewHolder = new ViewHolder();
				view = inflater.inflate(R.layout.cloud_coins_item, null);
				viewHolder.coins_num1 = (TextView) view.findViewById(R.id.coins_num1);
				viewHolder.coins_info_title1 = (TextView) view.findViewById(R.id.coins_info_title1);
				viewHolder.coins_info_img1 = (ImageView) view.findViewById(R.id.coins_info_img1);
				viewHolder.coins_title1 = (TextView) view.findViewById(R.id.coins_title1);
				viewHolder.navi_new_tip = (RelativeLayout) view.findViewById(R.id.navi_new_tip);

				view.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) view.getTag();

			}
			if ("1".equals(strFlag)) {
				if (position == 0) {
					if (rewardPositionList.contains("coin_reward_share")) {
						viewHolder.navi_new_tip.setVisibility(View.VISIBLE);
					} else {
						viewHolder.navi_new_tip.setVisibility(View.GONE);

					}
				}
				if (position == 1) {

					if (rewardPositionList.contains("coin_reward_praise")) {
						viewHolder.navi_new_tip.setVisibility(View.VISIBLE);
					} else {
						viewHolder.navi_new_tip.setVisibility(View.GONE);

					}

				}
				if (position == 2) {

					if (rewardPositionList.contains("coin_reward_comment")) {
						viewHolder.navi_new_tip.setVisibility(View.VISIBLE);
					} else {
						viewHolder.navi_new_tip.setVisibility(View.GONE);

					}
				}
				if (position == 3) {

					if (rewardPositionList.contains("coin_reward_hotShare")) {
						viewHolder.navi_new_tip.setVisibility(View.VISIBLE);
					} else {
						viewHolder.navi_new_tip.setVisibility(View.GONE);

					}

				}
				if (position == 4) {

					if (rewardPositionList.contains("coin_reward_redbag")) {
						viewHolder.navi_new_tip.setVisibility(View.VISIBLE);
					} else {
						viewHolder.navi_new_tip.setVisibility(View.GONE);

					}

				}

			} else if ("2".equals(strFlag)) {
				if (position == 0) {
					if (positionList.contains("coin_exchange_recharge")
							|| positionList.contains("coin_exchange_getCash")) {
						viewHolder.navi_new_tip.setVisibility(View.VISIBLE);
					} else {
						viewHolder.navi_new_tip.setVisibility(View.GONE);

					}
				}

				if (position == 1) {
					if (positionList.contains("coin_exchange_join")) {
						viewHolder.navi_new_tip.setVisibility(View.VISIBLE);
					} else {
						viewHolder.navi_new_tip.setVisibility(View.GONE);

					}
				}
			}

			imageLoader.displayImage(AppConfig.HOST + dataList.get(position).getLogo(), viewHolder.coins_info_img1,
					Constants.image_display_options, AppConfig.animateListener);
			viewHolder.coins_info_title1.setText(dataList.get(position).getTitle());
			if ("1".equals(strFlag)) {
				viewHolder.coins_title1.setText("奖励云豆");
			} else if ("2".equals(strFlag)) {
				viewHolder.coins_title1.setText("交易云豆");
			}
			viewHolder.coins_num1.setText(dataList.get(position).getCoin());

			return view;
		}

		class ViewHolder {

			TextView coins_num1, coins_info_title1, coins_title1;
			ImageView coins_info_img1;
			RelativeLayout navi_new_tip;
		}
	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

		Intent intent = new Intent(this, MoreInfoManagelActivity.class);
		intent.putExtra("csId", mCloudCoinsBeanList.get(position).getCsId());

		view.findViewById(R.id.navi_new_tip).setVisibility(View.GONE);
		if ("2".equals(strFlag)) {
			positionList.clear();
		} else if ("1".equals(strFlag)) {
			rewardPositionList.clear();
		}
		startActivity(intent);

	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		if (dialog == mDialogChoosePicture) {
			if (which == 0) {
				Intent intent = new Intent(this, CloudCoinsRechargeActivity.class);
				startActivity(intent);
			} else if (which == 1) {
				Intent intent = new Intent(this, CloudCoinsBankListActivity.class);
				startActivity(intent);
			}
		}

	}

}
